package de.bw.jeans.alarminfo.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.KeepAliveHttpTransportSE;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import de.bw.jeans.alarminfo.tools.AppPorpertiesData;

public class UnregisterDeviceFromFwStLeon extends AsyncTask<String, Boolean, Boolean> {

	Context context;
	
	public UnregisterDeviceFromFwStLeon(Context context) {
		this.context = context;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if(result) {
			// Den Benutzer über die erfolgreiche Deregistrierung informieren
			Toast toast = Toast.makeText(this.context, "Abmeldung erfolgreich!", Toast.LENGTH_LONG);
			toast.show();
		}
		else {
			// Den Benutzer über die gescheiterte Deregistrierung informieren
			Toast toast = Toast.makeText(this.context, "Abmeldung fehlgeschlagen!", Toast.LENGTH_LONG);
			toast.show();
		}
	}

	@Override
	protected Boolean doInBackground(String... params) {
		String METHOD_NAME = AppPorpertiesData.getAppProperties().getProperty("FW_UNREGISTER_METHOD_NAME");
		String SOAP_ACTION = AppPorpertiesData.getAppProperties().getProperty("FW_UNREGISTER_SOAP_ACTION");
		String NAMESPACE   = AppPorpertiesData.getAppProperties().getProperty("FW_UNREGISTER_NAMESPACE");
		String URL		   = AppPorpertiesData.getAppProperties().getProperty("FW_UNREGISTER_URL");

		Boolean rC = false;
		
		try {
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			
			SoapObject parameters = new SoapObject(NAMESPACE, METHOD_NAME);
			parameters.addProperty("device_id", params[0].toString());
			parameters.addProperty("app_name", AppPorpertiesData.getAppProperties().getProperty("APP_NAME_ID"));
			request.addProperty(METHOD_NAME, parameters);
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			
			HttpTransportSE httpTransportSE;
			if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
				// Da Markus Geider noch die Version 2.2.2 hat...
				httpTransportSE = new KeepAliveHttpTransportSE(URL);					
			}
			else {					
				httpTransportSE = new HttpTransportSE(URL);
			}
			httpTransportSE.call(SOAP_ACTION, envelope);
			
			SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
			
			if(result.toString().equals("true"))
				rC = true;
		}
		catch (Exception ex) {
			Log.d("AlarmInfo", "Fehler beim Deregistrieren des Device am WebService!");
		}
		
		return rC;
	}
	
	
	
}
